/* eslint-disable no-undef */
import axios from 'axios'
const qs = require('qs')
import { MessageBox } from 'element-ui'
import router from '../../router/index'
// const baseURL = process.env.NODE_ENV === 'development' ? '' : ''
axios.defaults.withCredentials = true
const service = axios.create({
  // baseURL,
  // timeout: 5000
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (sessionStorage.getItem('accessToken')) {
      config.headers.Authorization = sessionStorage.getItem('accessToken')
    }
    if (config.method === 'get') {
      //如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
      config.paramsSerializer = function (params) {
        return qs.stringify(params, {
          arrayFormat: 'repeat'
        })
      }
    }
    config.headers.withCredentials = true
    return config
  },
  (err) => {
    MessageBox.confirm('网络连接错误,请重新登录', '提示失败', {
      confirmButtonText: '知道了',
      type: 'warning',
      customClass: 'confirmTip',
      showCancelButton: false
    }).then(() => {
      sessionStorage.removeItem('accessToken')
      router.push('/login')
    })
    return Promise.reject(err)
  }
)

// 响应拦截

// 防止多个弹框提醒
let timer = null
service.interceptors.response.use(
  (response) => {
    // 如果是带有回调函数请求,则直接使用回调函数
    if (response.data.code === 401 && response.config.callback) {
      response.config.callback(response)
    } else if (response.status >= 200 && response.status < 300) {
      // console.log('response_', response)
      if (response.data.code === 401) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(function () {
          statusCode(response.data.msg, 401)
        }, 1)
      } else if (response.data === '系统异常') {
        return Promise.resolve({
          msg: '系统异常'
        })
      } else {
        return Promise.resolve(response.data)
      }
    }
  },
  (err) => {
    if (err.response.status && err.config.callback) {
      err.config.callback(err)
      return Promise.reject(err.response)
    }

    // console.log('err_', err.response)
    if (err.response.status) {
      switch (err.response.status) {
        case 401:
          statusCode('未授权，请重新登录', err.response.status)
          break
        case 403:
          statusCode('禁止访问')
          break
        case 404:
          statusCode('访问资源不存在')
          break
        case 500:
          statusCode('系统异常')
          break
        default:
          statusCode(err.response.data.error)
          break
      }
    }
    return Promise.reject(err.response)
  }
)

// 状态码错误捕获处理
function statusCode(msg, status) {
  MessageBox.confirm(msg, '提示失败', {
    confirmButtonText: '知道了',
    type: 'warning',
    customClass: 'confirmTip',
    showCancelButton: false
  })
    .then(() => {
      if (status === 401) {
        sessionStorage.clear()
        router.push('/login')
      }
    })
    .catch(() => {
      if (status === 401) {
        sessionStorage.clear()
        router.push('/login')
      }
    })
}
export default service
